﻿using System;
using System.Collections.Generic;
using System.Text;

namespace com.bodurov.NearestStarsVisualizer
{
    public static class Extensions
    {
        #region IList
        public static T Find<T>(this IList<T> list, Func<T,int,bool> predicate)
        {
            for (var i = 0; i < list.Count; i++)
            {
                var each = list[i];
                if (predicate(each, i))
                {
                    return each;
                }
            }
            return default(T);
        }
        #endregion


        #region IList<VectorUI>
        public static string ToLink(this IList<VectorUI> list, string rawPageUrl)
        {
            if(String.IsNullOrEmpty(rawPageUrl))
            {
                throw new Exception(SR.PageUrlCannotBeNullOrEmpty);
            }
            var qMarkIndex = rawPageUrl.IndexOf('?');
            var pageUrl = (qMarkIndex <= 0) ? rawPageUrl : rawPageUrl.Substring(0, qMarkIndex);
            var sb = new StringBuilder(pageUrl);
            if(list.Count > 0)
            {
                sb.Append("?vectors=");
            }
            var isFirst = true;
            foreach(var v in list)
            {
                if (isFirst)
                {
                    isFirst = false;
                }
                else
                {
                    sb.Append("v");
                }
                sb.AppendFormat("{0}/{1}/{2}/{3}/{4}/{5}",
                                v.BeginningX, v.BeginningY, v.BeginningZ,
                                v.EndX, v.EndY, v.EndZ);
            }
            return sb.ToString();
        }
        #endregion

        #region int
        public static byte GetA(this int pixel)
        {
            return (byte)((pixel >> 0x18) & 0xffL);
        }
        public static byte GetR(this int pixel)
        {
            return (byte)((pixel >> 0x10) & 0xffL);
        }
        public static byte GetG(this int pixel)
        {
            return (byte)((pixel >> 8) & 0xffL);
        }
        public static byte GetB(this int pixel)
        {
            return (byte)(pixel & 0xffL);
        }
        public static bool IsEqualToOrBetween(this int x, int n1, int n2)
        {
            return x >= Math.Min(n1, n2) && x <= Math.Max(n1, n2);
        }
        #endregion
    }
}
